<template>
  <div id="form-container">
    <el-steps :active="active" align-center finish-status="success">
      <el-step title="填写资料"></el-step>
      <el-step title="企业注册"></el-step>
      <el-step title="用户认证"></el-step>
      <el-step title="提交审核"></el-step>
    </el-steps>
    <transition name="slide-fade">

      <el-form v-if="active==1" :model="companyMsg" style="width: 100%;height: 80%;" ref="ruleForm" label-width="120px">
        <el-form-item
            prop="companyName"
            status-icon
            label="公司名称"
            :rules="[
       {required: true,message:'请输入所属企业名称',trigger:['blur','change']}
              ]"
        >
          <el-input size="small" v-model="companyMsg.companyName" placeholder="请输入内容"></el-input>
        </el-form-item>

        <el-form-item
            status-icon
            prop="industry"
            label="企业行业"
            :rules="[
      { required: true, message: '请输入企业行业', trigger: 'blur' }]"
        >
          <el-input size="small" placeholder="请输入公司行业" v-model="companyMsg.industry"></el-input>
        </el-form-item>

        <el-form-item
            status-icon
            prop="uniformCreditCode"
            label="统一社会信用码"
            :rules="[
      { required: true, message: '请输入统一社会信信用码', trigger: 'blur' }]"
        >
          <el-input size="small" placeholder="请输入统一社会信用码" v-model="companyMsg.uniformCreditCode"></el-input>
        </el-form-item>
        <el-form-item
            status-icon
            prop="registeredCapital"
            label="注册资金"
            :rules="[
      { required: true, message: '请输入注册资金', trigger: 'blur' }
    ]"
        >
          <el-input size="small" type="number" placeholder="请输入注册资金，单位为万" v-model="companyMsg.registeredCapital"></el-input>
        </el-form-item>
        <el-form-item
            prop="companyType"
            status-icon
            size="small"
            label="企业类型"
            :rules="[
       {required: true,message:'请选择企业类型',trigger:['blur','change']}
              ]"
        >
          <el-select v-model="companyMsg.companyType" placeholder="请选择">
            <el-option key="0" label="国企" value="0"></el-option>
            <el-option key="1" label="央企" value="1"></el-option>
            <el-option key="2" label="民企" value="2"></el-option>
            <el-option key="3" label="外资" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
            prop="cityCode"
            status-icon
            label="注册城市"
            :rules="[
       {required: true,message:'请选择所在城市',trigger:['blur','change']}
              ]"
        >
          <el-cascader
              size="small"
              :options="options"
              v-model="selectedOptions"
              filterable
              placeholder="请选择"
              @change="handleChange">
          </el-cascader>
        </el-form-item>
          <el-form-item>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
            <el-button @click="$router.push('/login')" type="danger">取消</el-button>
            <el-button @click="nextPage" style="float: right" type="primary">下一步</el-button>
          </el-form-item>
      </el-form>

      <el-form v-if="active==2"  :model="companyMsg" ref="ruleForm" style="width: 100%;height: 80%;" label-width="100px">
        <el-form-item
            status-icon
            prop="email"
            label="企业邮箱"
            :rules="[
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur'] }
    ]"
        >
          <el-input size="small" placeholder="请输入邮箱" v-model="companyMsg.email"></el-input>
        </el-form-item>
        <el-form-item
            prop="tel"
            status-icon
            label="企业电话"
            :rules="[
              {required: true,message:'输入企业电话',trigger:['blur']},
         ]"
        >
          <el-input size="small" placeholder="输入企业电话" type="number" v-model="companyMsg.tel"></el-input>
        </el-form-item>
        <el-form-item
            prop="address"
            status-icon
            label="详细地址"
            :rules="[
       {required: true,message:'输入地址',trigger:['blur']}
              ]"
        >
          <el-input size="small" placeholder="请输入详细地址" v-model="companyMsg.address"></el-input>
        </el-form-item>
        <el-form-item
            status-icon
            prop="legalPerson"
            label="法人代表"
            :rules="[
      { required: true, message: '请输入法人代表', trigger: 'blur' }
    ]"
        >
          <el-input size="small" placeholder="请输入法人代表" v-model="companyMsg.legalPerson"></el-input>
        </el-form-item>
        <el-form-item
            status-icon
            prop="buildTime"
            label="创立时间"
            :rules="[
      { required: true, message: '请选择日期', trigger: 'blur' }
    ]"
        >
          <el-date-picker size="small" type="date" placeholder="选择日期" :picker-options="pickerOptions"
                          v-model="companyMsg.buildTime"></el-date-picker>
        </el-form-item>
          <el-form-item label="认证材料">
            <div style="display: flex;justify-content:flex-start;width: 66%;">
              <el-upload
                  ref="upload"
                  :limit="1"
                  multiple
                  drag
                  action="#"
                  :on-change="handleblurFile"
                  :on-remove="handleRemove"
                  :on-exceed="handleExceed"
                  :file-list="fileList"
                  :http-request="uploadFile"
                  :auto-upload="false">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" style="margin-top: 0;line-height: 1" slot="tip">请上传营业执照等证明材料，不超过100Mb</div>
              </el-upload>
            </div>
          </el-form-item>
        <el-form-item>
          <el-form-item>
            <el-button @click="nextPage" style="float: right;margin-left: 10px" type="primary">下一步</el-button>
            <el-button @click="active--" type="danger" style="float: right">回退</el-button>
            <el-button @click="$router.push('/login')" type="danger" style="float: right">取消</el-button>
            <!--          <el-button type="primary" @click="submit()">提交</el-button>-->
            <el-button @click="resetForm('ruleForm')" style="float: right">重置</el-button>


          </el-form-item>
        </el-form-item>
      </el-form>

        <el-form v-if="active==3" :model="companyMsg"  style="width: 100%;height: 80%;" label-width="100px" ref="ruleForm">
          <el-form-item
              status-icon
              prop="realName"
              label="真实姓名"
              :rules="[
      { required: true, message: '请输入真实姓名', trigger: 'blur' },
    ]"
          >
            <el-input size="small" placeholder="请输入真实姓名" v-model="companyMsg.realName"></el-input>
          </el-form-item>
          <el-form-item
              status-icon
              prop="position"
              label="担任职位"
              :rules="[
      { required: true, message: '请输入担任职位', trigger: 'blur' }
    ]"
          >
            <el-input size="small" placeholder="请输入担任职位" v-model="companyMsg.position"></el-input>
          </el-form-item>
          <el-form-item
              status-icon
              prop="userEmail"
              label="个人邮箱"
              :rules="[
      { required: true, message: '请输入个人邮箱', trigger: 'blur' },
       { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur'] }
    ]"
          >
            <el-input size="small" placeholder="请输入个人邮箱" v-model="companyMsg.userEmail"></el-input>
          </el-form-item>

          <el-form-item
              status-icon
              prop="position"
              label="认证材料"
              height="300"
          ><div style="display: flex;justify-content:flex-start;width: 66%">
            <el-upload
                ref="upload"
                :limit="1"
                multiple
                drag
                action="#"
                :on-change="handleblurFile"
                :on-remove="handleRemove"
                :on-exceed="handleExceed"
                :file-list="fileList"
                :http-request="uploadUserFile"
                :auto-upload="false">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text" style="cursor: pointer;">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" style="margin-top: 0;line-height: 1" slot="tip">请上传证明您身份的证明材料，不超过100Mb</div>
            </el-upload>
          </div>
          </el-form-item>
          <el-form-item>
            <div style="width: 100%;height: 240px;display: flex;justify-content:flex-start;align-items:flex-end;">
              <el-button @click="$router.push('/login')" type="danger">取消</el-button>
              <el-button @click="back" type="danger">回退</el-button>
              <el-button @click="submit" style="float: right" type="primary">提交</el-button>
            </div>
          </el-form-item>
        </el-form>

      <div v-if="active==4" id="success">

        <h2 style="color: orange">提交成功!</h2><br>

        <p style="font-size: 14px;color: olive">审核结果将会通过邮件发送给您</p>
      </div>
    </transition>
  </div>

</template>

<script>
import {CodeToText, provinceAndCityData} from 'element-china-area-data'
import {isRename} from "@/network/companyUser";
import axios from "axios";
const token = localStorage.getItem("company_TOKEN")
axios.defaults.headers.common['TOKEN'] = token;
export default {
  name: "CompanyAuth",
  data() {
    return {
      options: provinceAndCityData,
      selectedOptions: [],
      active: 1,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      companyMsg: {
        companyId: 0,
        companyName: '',
        industry: "",
        uniformCreditCode: "",
        legalPerson: '',      //法人
        buildTime: '',     //注册时间
        email: '',      //企业邮箱,
        address: '',       //企业地址
        companyType: "",
        cityCode: "",
        tel: '',
        position:"",
        userEmail:'',
        realName:'',
        registeredCapital:''
      },
      id: '',
      fileData: '',  // 文件上传数据（多文件合一）
      fileList: [],   // upload多文件数组
      userFileData:''
    };
  },
  methods: {
    uploadFile(file) {
        this.fileData.append('file', file.file);  // append增加数据
    },
    uploadUserFile(file) {
      this.userFileData.append('file', file.file);  // append增加数据
    },
    nextPage() {
      if (this.active == 1) {
        // this.active++;
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            isRename(this.companyMsg.companyName).then(res => {
              if(res.data.code == 100){
                this.companyMsg.companyId = res.data.data.companyId;
                this.companyMsg.companyName = res.data.data.companyName;
                this.$message.success("该企业已注册，请直接进行用户认证");
                this.active = this.active+2;
              }
              if(res.data.code ==360){
                  this.active++;
              }
            })
          } else {
            return false;
          }
        });
      }
      if (this.active == 2) {
        // this.active++;
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            if (this.fileList.length === 0) {
              this.$message({
                message: '请选择认证文件',
                type: 'warning'
              })
            } else {
              const isLt100M = this.fileList.every(file => file.size / 1024 / 1024 < 100);
              if (!isLt100M) {
                this.$message.error('请检查，上传文件大小不能超过100MB');
              } else {
                this.fileData = new FormData();  // new formData对象
                this.$refs.upload.submit();  // 提交调用uploadFile函数
                this.fileData.append('industry', this.companyMsg.industry);
                this.fileData.append('uniformCreditCode', this.companyMsg.uniformCreditCode);
                this.fileData.append('legalPerson', this.companyMsg.legalPerson);
                this.fileData.append('buildTime', this.companyMsg.buildTime);
                this.fileData.append('email', this.companyMsg.email);
                this.fileData.append('address', this.companyMsg.address);
                this.fileData.append('companyType', this.companyMsg.companyType);
                this.fileData.append('cityCode', this.companyMsg.cityCode);
                this.fileData.append('tel', this.companyMsg.tel);
                this.fileData.append('registeredCapital', this.companyMsg.registeredCapital);  // 添加token
                axios.post("/api/company/register/upload/?ser=companyJob", this.fileData,).then((response) => {
                  if (response.data.code == 100) {
                      this.companyMsg.companyId = response.data.data.companyId;
                      this.$message.success("注册信息上传成功");
                    this.fileList = [];
                    this.active++;
                  } else {
                    this.$message.error(response.data.msg);
                    this.fileList=[];
                  }
                });
              }
            }
          } else {
            return false;
          }
        });
      }
    },
    handleChange(value) {
      if(CodeToText[value[1]]=='市辖区'){
        this.companyMsg.cityCode=value[0];
      }else{
        this.city=CodeToText[value[1]];
        this.companyMsg.cityCode=value[1];
      }
    },
    submit() {
      if (this.active == 3) {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            if (this.fileList.length === 0) {
              this.$message({
                message: '请选择认证文件',
                type: 'warning'
              })
            } else {
              const isLt100M = this.fileList.every(file => file.size / 1024 / 1024 < 100);
              if (!isLt100M) {
                this.$message.error('请检查，上传文件大小不能超过100MB');
              } else {
                this.userFileData = new FormData();  // new formData对象
                this.$refs.upload.submit();  // 提交调用uploadFile函数
                this.userFileData.append('companyId', this.companyMsg.companyId);  // 添加机构id
                this.userFileData.append('userName', this.companyMsg.userName); //  // 添加机构id
                this.userFileData.append('position', this.companyMsg.position);  // 添加token
                this.userFileData.append('userEmail', this.companyMsg.userEmail);  // 添加token
                this.userFileData.append('realName', this.companyMsg.realName);  // 添加token
                this.userFileData.append('companyName', this.companyMsg.companyName);  // 添加token
                axios.post("/api/user/register/upload/?ser=user", this.userFileData,).then((response) => {
                  if (response.data.code == 100) {
                    this.$message.success(response.data.data);
                    this.fileList = [];
                  } else {
                    this.$message.error(response.data.msg);
                    this.fileList=[];
                  }
                  this.active++;
                });
              }
            }
          } else {
            return false;
          }
        });
      }
    }
    ,//移除
    handleRemove(file, fileList) {
      this.fileList = fileList;
      return this.$confirm(`确定移除 ${ file.name }？`);
    },

    // 选取文件超过数量提示
    handleExceed() {
      // this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      this.$message.warning("文件已存在，请先移除")
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //监控上传文件列表
    handleblurFile(file, fileList) {
      let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name);
      if (existFile) {
        this.$message.error('当前文件已经存在!');
        fileList.pop();
      }
      this.fileList = fileList;
    },
    back(){
      if(this.companyId!=''){
        this.active=this.active-2;
      }
    }
  }
};

</script>

<style scoped>
#form-container {
  overflow: hidden;
  width: 100%;
  height: 100vh;
  box-shadow: 0 2px 4px gray;
  background-color: #fff;
  box-sizing: border-box;
  padding: 30px;
}

p {
  line-height: 30px;
}

#submit {
  position: fixed;
  left: 21%;
  bottom: 15%;
  width: 80px;
}

#success {
  width: 100%;
  height: 80%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

#material {
  padding: 10px;
  box-sizing: border-box;
  width: 100%;
  height: 80%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: gainsboro 1px dotted;
}

.slide-fade-enter-active {
  transition: all .2s ease;
  transition-delay: .2s;
}

.slide-fade-leave-active {
  transition: all .2s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}

.slide-fade-enter, .slide-fade-leave-to
  /* .slide-fade-leave-active for below version 2.1.8 */
{
  transform: translateX(20px);
  opacity: 0;
}
</style>
